﻿using System.IO;
using System.Threading.Tasks;
using Growatt.ShinebusServiceUploadPack.Model;
using Growatt.ShinebusServiceUploadPack.Service.OSS;
using Growatt.ShinebusServiceUploadPack.Service.OSS.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Growatt.ShinebusServiceUploadPack.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class FileUploadController : ControllerBase
    {
        private readonly IWebHostEnvironment _env;

        public FileUploadController(IWebHostEnvironment env)
        {
            _env = env;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadFile(List<IFormFile> files)
        {
            if (files == null || files.Count == 0)
                return BadRequest("没有文件被上传.");

            var uploads = Path.Combine(AppContext.BaseDirectory, "uploads");
            if (!Directory.Exists(uploads))
            {
                Directory.CreateDirectory(uploads);
            }

            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    var filePath = Path.Combine(uploads, file.FileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await file.CopyToAsync(stream);
                    }
                }
            }

            return Ok("文件上传成功.");
        }

        [HttpPost("FeishuEventRootobject")]
        public async Task<FeishuEventRootobjectResponse?> GetFeishuEventRootobjectAsync(FeishuEventRootobject productType)
        {
            return new FeishuEventRootobjectResponse() { challenge = productType.challenge };
        }
    }
}
